# -*- coding: utf-8 -*-
# This code written by ChanGOGOGO
"""
将通话记录中已经存在的大模型出参导出
"""
import pymysql
from util import (
    logging,
    json,
    write_excel,
    db_ip,
    db_port,
    db_username,
    db_password,
    excel_save_dir,
)


class ExportLLMOutput:
    def __init__(self, ui_data):
        self.conn = pymysql.connect(
            host=db_ip,
            port=db_port,
            user=db_username,
            passwd=db_password,
            charset="utf8",
        )
        self.cursor = self.conn.cursor()
        self.company_id = ui_data.get("company_id")
        self.business_id = ui_data.get("business_id")
        self.business = ui_data.get("business")
        self.data_type = ui_data.get("data_type")
        self.call_type = ui_data.get("call_type")
        self.data_month = ui_data.get("data_date")
        self.start_time = ui_data.get("start_time")
        self.end_time = ui_data.get("end_time")
        if self.call_type == "呼出":
            self.table_name = f"yicall_{self.company_id}.b_{self.business_id}_callout_session_ach_{self.data_month} "
            self.excel_title = ["拨打时间", "被叫号码", "挂断节点", "用户意向"]
        else:
            self.table_name = f"yicall_{self.company_id}.b_{self.business_id}_callout_session_in_ach_{self.data_month} "
            self.excel_title = ["拨打时间", "主叫号码", "挂断节点", "用户意向"]

    def query_db_data(self):
        """"""
        sql = (
            f"SELECT DATE_FORMAT(callout_dial_time, '%Y-%m-%d %H:%m:%S'),dial_number,callout_last_node_name,"
            f"dialog_user_prefer, llm_analyse_info FROM {self.table_name} WHERE callout_connect_status = 100 AND "
            f"callout_finish_time BETWEEN '{self.start_time}' AND '{self.end_time}';"
        )
        logging.info(f"执行查询{self.business}{self.data_type}SQL：\n{sql}")
        self.cursor.execute(sql)
        result = self.cursor.fetchall()
        self.close_db()
        return result

    def close_db(self):
        self.cursor.close()
        self.conn.close()

    def export(self):
        db_data = self.query_db_data()
        if len(db_data) < 1:
            msg = (
                f"<font color=green>无法导出“{self.business}”的【{self.data_type}】，"
                f"原因：\n在{self.start_time}至{self.end_time}没有{self.call_type}数据！</font>"
            )
            return {"code": 1, "excel_names": None, "msg": msg}
        else:
            excel_data = []
            for single_data in db_data:
                (
                    dial_time,
                    dial_number,
                    last_node_name,
                    user_prefer,
                    llm_analyse_info,
                ) = single_data
                current_excel_title_len = len(self.excel_title)
                one_row_value = [dial_time, dial_number, last_node_name, user_prefer]
                for x in range(current_excel_title_len - 4):
                    one_row_value.append("")
                # 处理大模型的出参
                if llm_analyse_info:
                    llm_analyse_info = json.loads(llm_analyse_info)
                    for analyse_item, analyse_value in llm_analyse_info.items():
                        fact_llm_excel_title = f"大模型-{analyse_item}"
                        if fact_llm_excel_title not in self.excel_title:
                            self.excel_title.append(fact_llm_excel_title)
                            one_row_value.append(analyse_value)
                        else:
                            title_index = self.excel_title.index(fact_llm_excel_title)
                            one_row_value[title_index] = analyse_value
                excel_data.append(one_row_value)
            file_name = f"{self.business}_({self.call_type}){self.data_type}"
            excel_name = write_excel(
                [["大模型出参", self.excel_title, excel_data]],
                excel_save_dir,
                file_name,
            )
            return {"code": 0, "excel_names": [excel_name], "msg": None}


if __name__ == "__main__":
    ...
